<template>
  <div class="venue-detail">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <span class="page-title">场地详情</span>
      </template>
    </el-page-header>

    <div v-loading="loading" class="content">
      <el-row :gutter="20">
        <!-- 主要内容 -->
        <el-col :span="16">
          <!-- 基本信息 -->
          <el-card class="info-card">
            <template #header>
              <span class="card-title">基本信息</span>
            </template>
            
            <div class="venue-header">
              <el-image 
                :src="venue.coverImage || '/default-venue.png'" 
                fit="cover"
                class="cover"
              />
              <div class="header-info">
                <h2>{{ venue.name }}</h2>
                <div class="meta">
                  <el-tag :type="getStatusType(venue.status)">{{ getStatusText(venue.status) }}</el-tag>
                  <el-tag v-if="venue.isVerified" type="success" class="ml-2">已认证</el-tag>
                  <el-rate 
                    v-model="venue.rating" 
                    disabled 
                    show-score 
                    text-color="#ff9900" 
                    score-template="{value}"
                    class="ml-2"
                  />
                </div>
              </div>
            </div>

            <el-descriptions :column="2" border class="mt-4">
              <el-descriptions-item label="场地ID">{{ venue.id }}</el-descriptions-item>
              <el-descriptions-item label="类别">
                <el-tag>{{ venue.category || '其他' }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="运动类型" :span="2">
                {{ venue.sportTypes || '暂无' }}
              </el-descriptions-item>
              <el-descriptions-item label="容纳人数">{{ venue.capacity || 0 }}人</el-descriptions-item>
              <el-descriptions-item label="场地面积">
                {{ venue.area ? `${venue.area} 平方米` : '未设置' }}
              </el-descriptions-item>
              <el-descriptions-item label="地址" :span="2">
                <el-icon><Location /></el-icon>
                <span>{{ venue.city }} {{ venue.district }} {{ venue.address }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="联系电话">
                <el-icon><Phone /></el-icon>
                <span>{{ venue.phone }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="电子邮箱">
                <el-icon><Message /></el-icon>
                <span>{{ venue.email || '未设置' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="营业时间" :span="2">
                {{ venue.businessHours || '未设置' }}
              </el-descriptions-item>
              <el-descriptions-item label="管理员ID">{{ venue.managerId }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDate(venue.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="设施设备" :span="2">
                <div class="facilities">
                  {{ venue.facilities || '暂无' }}
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="价格信息" :span="2">
                <div class="price-info">
                  {{ venue.priceInfo || '暂无' }}
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="场地描述" :span="2">
                <div class="description">{{ venue.description || '暂无描述' }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 预订记录 -->
          <el-card class="bookings-card mt-3">
            <template #header>
              <div class="card-header">
                <span class="card-title">预订记录</span>
                <el-button size="small" @click="loadBookings">刷新</el-button>
              </div>
            </template>

            <el-empty v-if="bookings.length === 0" description="暂无预订记录" />
            <el-table v-else :data="bookings" stripe>
              <el-table-column prop="id" label="预订ID" width="100" />
              <el-table-column prop="eventId" label="活动ID" width="100" />
              <el-table-column label="预订时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.startTime) }} 至 {{ formatDateTime(row.endTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="userId" label="预订人ID" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getBookingStatusType(row.status)">
                    {{ getBookingStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 侧边栏 -->
        <el-col :span="8">
          <!-- 快速操作 -->
          <el-card class="action-card">
            <template #header>
              <span class="card-title">快速操作</span>
            </template>
            <el-space direction="vertical" :size="12" style="width: 100%">
              <el-button 
                type="primary" 
                style="width: 100%" 
                @click="editVenue"
              >
                编辑场地
              </el-button>
              <el-button 
                type="warning" 
                style="width: 100%" 
                @click="updateStatus"
              >
                更新状态
              </el-button>
              <el-button 
                type="danger" 
                style="width: 100%" 
                @click="deleteVenue"
              >
                删除场地
              </el-button>
            </el-space>
          </el-card>

          <!-- 统计信息 -->
          <el-card class="stats-card mt-3">
            <template #header>
              <span class="card-title">统计信息</span>
            </template>
            <div class="stat-item">
              <span class="stat-label">总预订次数</span>
              <span class="stat-value">{{ venue.totalBookings || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">综合评分</span>
              <span class="stat-value">{{ venue.rating || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">评价数量</span>
              <span class="stat-value">{{ venue.reviewCount || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">容纳人数</span>
              <span class="stat-value">{{ venue.capacity || 0 }}人</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">场地面积</span>
              <span class="stat-value">{{ venue.area || 0 }}㎡</span>
            </div>
          </el-card>

          <!-- 位置信息 -->
          <el-card class="location-card mt-3">
            <template #header>
              <span class="card-title">位置信息</span>
            </template>
            <div class="location-info">
              <p><strong>城市：</strong>{{ venue.city }}</p>
              <p><strong>区域：</strong>{{ venue.district }}</p>
              <p><strong>经度：</strong>{{ venue.longitude || '未设置' }}</p>
              <p><strong>纬度：</strong>{{ venue.latitude || '未设置' }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 更新状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新场地状态" width="400px">
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="statusForm.status" style="width: 100%">
            <el-option label="营业中" value="active" />
            <el-option label="暂停营业" value="inactive" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateStatus">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { venueApi } from '@/api/venue'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const venue = ref({})
const bookings = ref([])
const statusDialogVisible = ref(false)

const statusForm = reactive({
  status: ''
})

const venueId = computed(() => route.params.id)

onMounted(() => {
  loadVenueDetail()
  loadBookings()
})

const loadVenueDetail = async () => {
  loading.value = true
  try {
    venue.value = await venueApi.getVenueDetail(venueId.value)
  } catch (error) {
    console.error('加载场地详情失败:', error)
    ElMessage.error('加载场地详情失败')
  } finally {
    loading.value = false
  }
}

const loadBookings = async () => {
  try {
    bookings.value = await venueApi.getVenueBookings(venueId.value)
  } catch (error) {
    console.error('加载预订记录失败:', error)
    bookings.value = []
  }
}

const editVenue = () => {
  router.push(`/venues/edit/${venueId.value}`)
}

const updateStatus = () => {
  statusForm.status = venue.value.status
  statusDialogVisible.value = true
}

const confirmUpdateStatus = async () => {
  try {
    await venueApi.updateVenueStatus(venueId.value, statusForm.status)
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    loadVenueDetail()
  } catch (error) {
    console.error('更新失败:', error)
  }
}

const deleteVenue = () => {
  ElMessageBox.confirm('确定要删除该场地吗？此操作不可恢复', '警告', {
    type: 'error'
  }).then(async () => {
    try {
      await venueApi.deleteVenue(venueId.value)
      ElMessage.success('删除成功')
      router.push('/venues')
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

const goBack = () => {
  router.back()
}

const getStatusType = (status) => {
  const types = { active: 'success', inactive: 'warning', maintenance: 'info' }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = { active: '营业中', inactive: '暂停营业', maintenance: '维护中' }
  return texts[status] || status
}

const getBookingStatusType = (status) => {
  const types = { confirmed: 'success', pending: 'warning', cancelled: 'info' }
  return types[status] || ''
}

const getBookingStatusText = (status) => {
  const texts = { confirmed: '已确认', pending: '待确认', cancelled: '已取消' }
  return texts[status] || status
}

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

const formatDateTime = (date) => {
  return date ? dayjs(date).format('MM-DD HH:mm') : '-'
}
</script>

<style scoped>
.venue-detail {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
}

.venue-header {
  display: flex;
  gap: 20px;
}

.cover {
  width: 200px;
  height: 150px;
  border-radius: 8px;
  flex-shrink: 0;
}

.header-info h2 {
  margin: 0 0 12px 0;
  font-size: 24px;
}

.meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ml-2 {
  margin-left: 8px;
}

.mt-3 {
  margin-top: 16px;
}

.mt-4 {
  margin-top: 20px;
}

.card-title {
  font-weight: 600;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.facilities,
.price-info,
.description {
  line-height: 1.6;
  white-space: pre-wrap;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: 600;
  color: #303133;
}

.location-info p {
  margin: 8px 0;
  color: #606266;
}
</style>

